<script setup>
import {Lock, User} from "@element-plus/icons-vue";
import {ref} from "vue";
import {ElMessage} from "element-plus";
import {useOrderInfoStore, useUserStore} from "@/stores/index.js";
import {useRouter} from "vue-router";
import {userLoginService} from "@/api/user.js";

// 判断渲染哪个组件
const isRegister = defineModel()
// 收集表单数据
const formModel = ref({
  username: 'zhangsan',
  password: '123456'
})
// 表单对象
const form = ref()
// 表单数据校验规则
const rules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 5, max: 10, message: '用户名必须是5-10位的字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    }
  ]
}
// 使用仓库
const userStore = useUserStore()
// 创建路由对象
const router = useRouter()
// 储存用户id
const orderStore = useOrderInfoStore()
// 用户登录
const login = async () => {
  // 表单预校验
  await form.value.validate()
  // 调用的登录方法
  const res = await userLoginService(formModel.value)
      .catch((err) => console.log(err))
  // 设置用户id
  orderStore.setUserId(res.data.id)
  // 设置token
  userStore.setToken(res.data.token)
  // 设置用户名
  userStore.setName(res.data.name)
  // 跳转到首页
  router.push('/')
  // 提示
  ElMessage.success('登录成功')
}
</script>

<template>
  <el-form
      :model="formModel"
      :rules="rules"
      ref="form"
      size="large"
      autocomplete="off"
      @keyup.enter="login"
  >
    <el-form-item>
      <h1>登录</h1>
    </el-form-item>
    <el-form-item prop="username">
      <el-input
          v-model="formModel.username"
          :prefix-icon="User"
          placeholder="请输入用户名"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
          v-model="formModel.password"
          name="password"
          :prefix-icon="Lock"
          type="password"
          placeholder="请输入密码"
      ></el-input>
    </el-form-item>
    <el-form-item class="flex">
      <div class="flex">
        <el-checkbox>记住我</el-checkbox>
        <el-link
            @click="isRegister = 3"
            type="primary"
            :underline="false">忘记密码？</el-link>
      </div>
    </el-form-item>
    <el-form-item>
      <el-button @click="login" class="button" type="primary" auto-insert-space
      >登录
      </el-button
      >
    </el-form-item>
    <el-form-item class="flex">
      <el-link type="info" :underline="false" @click="isRegister = 2">
        注册 →
      </el-link>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  user-select: none;

  .title {
    margin: 0 auto;
  }

  .button {
    width: 100%;
  }

  .flex {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}
</style>
